<!--
 * @Description: 份额维护
 * @Author: wangwangwang
 * @Date: 2020-09-21 14:09:06
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-12-29 14:29:54
-->
<template>
  <div class="pages_content table">
    <el-container>
      <el-header>
        <breaDcrumb />
      </el-header>
      <el-main style="display:flex">
        <div v-loading="treeLoading" class="tree">
          <el-tree ref="tree" :data="treeData" default-expand-all :expand-on-click-node="false">
            <span slot-scope="{ node,data }" class="custom-tree-node tree-line">
              <span v-if="data.children">
                <i :class="data.icon"></i>
                <span>{{ node.label }}</span>
              </span>
              <el-radio-group v-else v-model="activetree" @change="treeSelect">
                <el-radio :label="data.value">
                  <span>{{ node.label }}</span>
                </el-radio>
              </el-radio-group>
            </span>
          </el-tree>
        </div>
        <div>
          <div class="header_right" @click="showCardNav = !showCardNav">
            <div class="title">搜索</div>
            <div>
              <transition name="from"></transition>
              <span v-show="!showCardNav">
                <i style="margin-right: 5px;" class="el-icon-arrow-down"></i>
              </span>
              <transition name="to"></transition>
              <span v-show="showCardNav">
                <i style="margin-right: 5px;" class="el-icon-arrow-up"></i>
              </span>
            </div>
          </div>
          <div v-show="showCardNav" class="hr"></div>
          <el-collapse-transition>
            <div v-show="showCardNav">
              <div class="search">
                <span style="display: inline-block;margin-bottom: 10px;">
                  <span style="margin-right: 12px;">原物料名称</span>
                  <el-input v-model="tableParam.rawName" style="width: 240px;" clearable placeholder="请输入" @keyup.enter.native="gettableData()" />
                </span>
                <span style="margin-left: 24px;">
                  <span style="margin-right: 12px;">状态</span>
                  <el-select v-model="tableParam.maintainStatus" placeholder="请选择">
                    <el-option label="正常" :value="1"></el-option>
                    <el-option label="审核中" :value="2"></el-option>
                    <el-option label="不通过" :value="3"></el-option>
                  </el-select>
                </span>
                <el-button icon="el-icon-search" size="medium" class="bottom_all but1" @click="(tableParam.page = 1), gettableData()">查 询</el-button>
                <el-button size="medium" class="bottom_all_two" style="margin-left:12px;" @click="init()">重 置</el-button>
              </div>
            </div>
          </el-collapse-transition>
          <div class="hr"></div>
          <div class="card">
            <div class="card_nav">
              <div>
                <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='TIANJIA'))!==-1" size="small" class="bottom_all" style="margin-left: 0;" @click="pagesaddFromDate()">
                  <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
                  添加
                </el-button>
              </div>
              <div>
                <el-dropdown :hide-on-click="false" trigger="click" style="margin: 0 20px;">
                  <el-link :underline="false">
                    <span class="el-icon--left">
                      <i class="iconfont iconicon_button_filtrate"></i>
                    </span>
                    筛选
                  </el-link>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item, index) in table" :key="index">
                      <el-checkbox v-model="item.status">{{ item.label }}</el-checkbox>
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </div>
            <div v-loading="tableLoading" class="card_info" :style="style">
              <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableData" tooltip-effect="dark">
                <template v-for="(item, index2) in table">
                  <el-table-column v-if="item.status" :key="index2" :label="item.label" align="center" :width="item.width">
                    <template slot-scope="scope">
                      <el-button v-if="item.label == '份额详情'&&ButtonList.findIndex(res=>(res.buttonValue=='FENEXIANGQING'))!==-1" size="mini" class="bottom_one" @click="changitem(scope.row, 'LotAllots')">份额详情</el-button>
                      <span v-else-if="item.label == '状态'">{{ scope.row.maintainStatus == 1 ? '正常' : scope.row.maintainStatus == 2 ? '审核中' : '不通过' }}</span>
                      <span v-else-if="item.label == '操作'">
                        <el-button v-if="ButtonList.findIndex(res=>(res.buttonValue=='XIUGAI'))!==-1" class="bottom_one" size="mini" @click="pagesupdateFromDate(scope.row)">
                          <i class="icon iconfont iconicon_button_modification" style="font-size: 12px;"></i>
                          修改
                        </el-button>
                      </span>
                      <span v-else>{{ scope.row[item.prop] }}</span>
                    </template>
                  </el-table-column>
                </template>
              </el-table>
            </div>
          </div>
        </div>
      </el-main>
      <div class="card_bottom">
        <div class="card_bottom_left">
          <div class="top_page_totle">总共{{ total }}条</div>
          <el-pagination :current-page.sync="tableParam.page" :page-size="tableParam.pageSize" :page-sizes="[10, 20, 30, 40,50,100,200,500,1000]" layout="prev,pager,sizes,next,jumper" :total="total" @size-change="sizeChange" @current-change="gettableData()"></el-pagination>
        </div>
        <div>
          <el-button size="mini" icon="el-icon-refresh-right" class="bottom_all_two" @click="gettableData">刷新</el-button>
        </div>
      </div>
    </el-container>
    <!-- 添加 -->
    <el-dialog v-dialogDrag :visible.sync="addDialog" width="1180px" :close-on-click-modal="false" :before-close="resetFromDate">
      <span slot="title" class="dialog-title">{{ addDialogTitle }}</span>
      <div class="dialoginfo">
        <div class="dialoginfo-title">
          <div>
            <span>公司：{{ fromDate.lotMaintain.company }}</span>
            <span></span>
          </div>
          <div>
            <span>站点：{{ fromDate.lotMaintain.station }}</span>
            <span></span>
          </div>
        </div>
        <el-form ref="reffromDate" :inline="true" :model="fromDate.lotMaintain" :rules="rules">
          <el-form-item prop="rawId">
            <span slot="label" style="color:#FF0000;">原物料名称</span>
            <el-select v-model="fromDate.lotMaintain.rawId" placeholder="请选择" :disabled="addDialogTitle=='修改'" @change="gettcontract">
              <el-option v-for="(item, index) in rawIdlist" :key="index" :label="item.itemName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <div style="padding-bottom: 10px;">
            <el-button size="mini" class="bottom_all" style="margin-left: 0;" :disabled="list.length==0" @click="addItem()">
              <i class="icon iconfont iconicon_button_add" style="font-size: 12px;"></i>
              添加
            </el-button>
          </div>
          <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="fromDate.list" tooltip-effect="dark">
            <el-table-column label="原物料合同编号" align="center" prop :min-width="160">
              <template slot-scope="scope">
                <el-select v-model="scope.row.contractId" placeholder="请选择" style="width: 100%;" @change="changeitem(scope.row)">
                  <el-option v-for="(item, index) in list" :key="index" :label="`${item.contractNo}+${item.supplier}`" :value="item.contractId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="合同签订主体" align="center" prop="contractSigningSubject" :min-width="140"></el-table-column>
            <el-table-column label="供应商" align="center" prop="supplier" :min-width="140"></el-table-column>
            <el-table-column label="原物料" align="center" :min-width="160">
              <template slot-scope="scope">
                <el-select v-model="scope.row.rawMaterialsId" placeholder="请选择" style="width: 100%;" @change="changearritem(scope.row,scope.$index)">
                  <el-option v-for="(item, index) in scope.row.arr" :key="index" :label="item.brand+item.productName+item.specification" :value="item.productId"></el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="品牌" align="center" prop="brand"></el-table-column>
            <el-table-column label="规格" align="center" prop="specification"></el-table-column>
            <el-table-column label="份额（%）" align="center">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.lotNum" style="width:100%" :precision="0" :controls="false" :max="100"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="left" width="100">
              <template slot-scope="scope">
                <el-button size="mini" class="bottom_two" @click="delItem(scope.$index)">
                  <i class="icon iconfont iconicon_button_delete" style="font-size: 12px;"></i>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetFromDate">取 消</el-button>
        <el-button class="bottom_all" style="margin-left: 24px;" @click="pagessubmitFromDate()">提交审核</el-button>
      </span>
    </el-dialog>
    <!-- 份额审批 -->
    <el-dialog v-dialogDrag :visible.sync="elDialog.indexOf(activeDialog) == 0" width="680px" :close-on-click-modal="false" :before-close="resetDialog">
      <span slot="title" class="dialog-title">份额维护</span>
      <div class="dialoginfo" style="padding-top: 0;">
        <div class="dialoginfo-title">
          <div>
            <span>公司：</span>
            <span>{{ low.company }}</span>
          </div>
          <div>
            <span>站点：</span>
            <span>{{ low.station }}</span>
          </div>
          <div>
            <span>原物料名称：</span>
            <span>{{ low.rawName }}</span>
          </div>
        </div>
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableDialog" tooltip-effect="dark">
          <el-table-column label="原物料合同编号" align="center" prop="contractNo"></el-table-column>
          <el-table-column label="供应商" align="center" prop="supplier"></el-table-column>
          <el-table-column label="份额（%）" align="center" prop="lotNum"></el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetDialog">取 消</el-button>
      </span>
    </el-dialog>
    <el-dialog v-dialogDrag :visible.sync="elDialog.indexOf(activeDialog) == 1" width="680px" :close-on-click-modal="false" :before-close="resetDialog">
      <span slot="title" class="dialog-title">份额维护审批</span>
      <div class="dialoginfo" style="padding: 0;">
        <el-table :header-cell-style="{ background: '#f3f6f9' }" :cell-style="{ borderRight: 'none' }" border stripe style="width:100%" :data="tableDialog" tooltip-effect="dark">
          <el-table-column label="提交时间" align="center" prop="createTime"></el-table-column>
          <el-table-column label="审批结果" align="center" prop="supplier">
            <template slot-scope="scope">{{ scope.row.type == 1 ? '正常' : scope.row.type == 2 ? '审核中' : '不通过' }}</template>
          </el-table-column>
          <el-table-column label="审批时间" align="center" prop="updateTime"></el-table-column>
          <el-table-column label="审批意见" align="center" prop="remark"></el-table-column>
        </el-table>
        <div style="display: flex;align-items: center;height: 60px;">
          <div>总共{{ Dialogtotal }}条</div>
          <el-pagination :current-page.sync="DialogParam.page" :page-size="DialogParam.pageSize" layout="prev, pager, next, jumper" :total="Dialogtotal" @current-change="gettableData()"></el-pagination>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="bottom_all_two" @click="resetDialog">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import mixin from "@/mixins/ICPSmixin.js";
import { getDicType } from "@/api/common.js";
import {
  queryPage,
  batchUpdateOrDelete,
  saveOrUpdate,
  Download,
  getLotAllots,
  getauditLot,
  getContracts,
} from "@/api/GHnumber/share.js";
import { setTimeout } from 'timers';
import { getUserAutList, get_simple_organization } from "@/api/common.js";
export default {
  mixins: [mixin],
  data() {
    return {
      UserInfo: '',
      activetree: '',
      stationIdlist: [],
      /*表格增删改查及下载接口*/
      queryPage: queryPage,
      batchUpdateOrDelete: batchUpdateOrDelete,
      saveOrUpdate: saveOrUpdate,
      DownloadURL: Download,
      /*表格数据*/
      table: [
        { label: "份额维护ID", width: "auto", prop: "code", status: true },
        { label: "原物料名称", width: "auto", prop: "rawName", status: true },
        { label: "份额详情", width: "auto", prop: "", status: true },
        { label: "状态", width: "auto", prop: "", status: true },
        { label: "操作", width: "220", prop: "", status: true },
      ],
      /*表单页类型，0为无树状，1为有树状，有树状在el-main加上display:flex*/
      pagesType: 1,
      /*添加表单数据*/
      rules: {
        rawId: [{ required: true, message: "请选择原物料", trigger: "change" }],
      },
      fromDate: {
        lotMaintain: {
          rawId: "",
        },
        list: [],
      },
      treeData: [],
      elDialog: ["LotAllots", "auditLot"],
      activeDialog: "",
      low: {},
      tableDialog: [],
      DialogParam: {
        page: 1,
        pageSize: 9,
      },
      Dialogtotal: null,
      rawIdlist: [],
      list: [],
      fromDateList: [],
      keyId: '',
    };
  },
  async created() {
    this.treeData = await getUserAutList()
    this.activetree = this.treeData[0].children[0].value;
    this.tableParam.stationId = this.treeData[0].children[0].value;
    this.fromDate.lotMaintain.stationId = this.treeData[0].children[0].value
    this.fromDate.lotMaintain.station = this.treeData[0].children[0].label
    this.treeLoading = false;
    this.fromDate.lotMaintain.companyId = this.treeData[0].value
    this.fromDate.lotMaintain.company = this.treeData[0].label
    this.gettableData();

    /*存储拷贝的原初始化fromDate数据*/
    this.tableParam = { ...this.tableParam, rawName: "", maintainStatus: "" };
    getDicType({ code: "MATname" }).then((res) => {
      this.rawIdlist = res.data.items;
    });
  },
  /*
   *copy(data)深拷贝数据,返回拷贝完的数据
   *gettableData获取列表数据
   *load下载
   *SortNum保持序列号
   * UpdateOrDelete禁用，启用，删除
   * submitFromDate保存更新数据
   */
  methods: {
    /*添加*/
    pagesaddFromDate() {
      this.rules = {
        rawId: [{ required: true, message: "请选择原物料", trigger: "change" }],
      };
      this.$data.fromDate.list = [];
      this.fromDate.lotMaintain.rawId = "";
      if (!this.fromDate.lotMaintain.stationId) {
        this.$message({
          message: "警告哦，请选择站点后添加",
          type: "warning",
        });
        return;
      }
      this.addDialog = true;
      this.addDialogTitle = "添加";
      this.keyId = '';
      setTimeout(() => {
        this.$refs.reffromDate.clearValidate();
      }, 10)
    },
    gettcontract() {
      setTimeout(() => {
        this.$refs.reffromDate.clearValidate();
        if (this.tableData.findIndex(res => (res.rawId == this.fromDate.lotMaintain.rawId)) !== -1 && this.addDialogTitle == '添加') {
          this.$message({
            message: '警告哦，请选择无分配份额的原物料',
            type: 'warning'
          });
          this.list = [];
          return
        }
        this.fromDate.lotMaintain.rawName = this.$fromatTable(
          this.rawIdlist,
          this.fromDate.lotMaintain.rawId,
          "id",
          "itemName"
        );
        let data = {
          id: this.fromDate.lotMaintain.rawId,
          stations: this.fromDate.lotMaintain.stationId,
        };
        getContracts(data).then((res) => {
          if (res.code === 1001) {
            if (!res.data.length) {
              this.$message.warning('没有找到可用合同');
            }
            this.list = res.data;
            if (this.addDialogTitle == "添加") {
              this.fromDate.list = [];
            }
          }
        });
      }, 10)

    },
    /*修改*/
    pagesupdateFromDate(low) {
      this.rules = {};
      this.fromDate.lotMaintain.company = low.company;
      this.fromDate.lotMaintain.companyId = low.companyId;
      this.fromDate.lotMaintain.station = low.station;
      this.fromDate.lotMaintain.stationId = low.stationId;
      this.fromDate.lotMaintain.rawName = low.rawName;
      this.fromDate.lotMaintain.rawId = low.rawId;
      this.keyId = low.id;
      getLotAllots({ id: low.id }).then((res) => {
        this.fromDate.list = res.data.map((res) => {
          let obj = new Object();
          obj.id = res.id;
          obj.contractNo = res.contractNo;
          obj.contractId = res.contractId;
          obj.supplier = res.supplier;
          obj.isCarriage = res.isCarriage;
          obj.supplierId = res.supplierId;
          obj.rawMaterialsId = res.rawMaterialsId;
          obj.rawMaterialsName = res.rawMaterialsName;
          obj.brand = res.brand;
          obj.specification = res.specification;
          obj.lotNum = res.lotNum;
          obj.type = 2;
          obj.arr = res.list;
          return obj;
        });
        this.fromDateList = this.copy(this.fromDate.list);
        this.gettcontract();
        this.addDialogTitle = "修改";
        this.addDialog = true;
      });
    },
    addItem() {
      if (this.fromDate.lotMaintain.rawId) {
        let data = {
          contractNo: "",
          contractId: "",
          supplier: "",
          supplierId: "",
          rawMaterialsId: "",
          brand: "",
          specification: "",
          lotNum: "",
          type: 1,
          isCarriage: 0,
          arr: [],
        };
        this.fromDate.list.push(data);
        console.log(this.fromDate.list);
      } else {
        this.$message({
          message: "警告哦，请先x选择原物料",
          type: "warning",
        });
      }
    },
    delItem(index) {
      console.log(index);
      this.fromDate.list.splice(index, 1);
    },
    changeitem(e) {
      let item = this.list.find((res) => res.contractId == e.contractId);
      e.contractNo = item.contractNo;
      e.supplier = item.supplier;
      e.supplierId = item.supplierId;
      e.isCarriage = item.isCarriage;
      e.arr = item.list;
      e.rawMaterialsId = "";
      e.rawMaterialsName = "";
      e.brand = "";
      e.specification = "";
    },
    changearritem(e, index) {
      let type = this.contractIdAndRawMaterialsIdFun(e, index)
      if (type) {
        this.$message({
          message: '合同+原物料；只能存在唯一一条',
          type: 'warning'
        });
        e.rawMaterialsId = ''
      } else {
        let item = e.arr.find((res) => res.productId == e.rawMaterialsId);
        e.rawMaterialsName = item.productName;
        e.brand = item.brand;
        e.specification = item.specification;
      }
    },
    contractIdAndRawMaterialsIdFun(e, index) {
      let id = e.contractId + e.rawMaterialsId
      let type = false
      this.fromDate.list.forEach((v, k) => {
        let listId = v.contractId + v.rawMaterialsId
        if (id == listId && k != index) {
          type = true
        }
      })
      return type
    },
    init() {
      /*重置数据*/
      this.tableParam.rawName = "";
      this.tableParam.maintainStatus = "";
      this.gettableData();
    },
    treeSelect() {
      this.tableParam.stationId = this.$refs.tree.getCurrentNode().value;
      this.fromDate.lotMaintain.stationId = this.$refs.tree.getCurrentNode().value;
      this.fromDate.lotMaintain.station = this.$refs.tree.getCurrentNode().label;
      get_simple_organization({ id: this.tableParam.stationId }).then((res) => {
        this.fromDate.lotMaintain.companyId = res.data.id
        this.fromDate.lotMaintain.company = res.data.name
      });//查询站点所属公司
      this.gettableData();
    },
    changevompany(res) {
      this.tableParam.stationId = "";
      this.fromDate.lotMaintain.stationId = "";
      this.tableParam.companyId = res.companyId;
      this.fromDate.lotMaintain.companyId = res.companyId;
      this.fromDate.lotMaintain.company = res.comPanyName;
    },
    pagessubmitFromDate() {
      let _this = this;
      if (_this.fromDate.list.length == 0) {
        _this.$message({
          message: "请掷筛添加一条记录",
          type: "warning",
        });
        return;
      }
      let allHasData = _this.fromDate.list.filter((item) =>
        this.fromDateList.some((items) => item.id == items.id)
      );
      let deleteData = this.fromDateList.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      let addData = _this.fromDate.list.filter(
        (item) => !allHasData.some((items) => item.id == items.id)
      );
      deleteData.forEach((res) => {
        res.type = 0;
      });
      const copyList = [...allHasData, ...deleteData, ...addData];
      let num100 = 0
      copyList.forEach((v) => {
        if (v.type!==0)
        num100 = num100 + v.lotNum
        if (v.rawMaterialsId == '') {
          _this.$message({
            message: "数据未填写完整！",
            type: "warning",
          });
          return
        }
      })
      if (num100!==100) {
        _this.$message({
          message: "份额的和不是100%，请检查数据。",
          type: "warning",
        });
        return
      }
      _this.fromDate.list = copyList;
      console.log(_this.fromDate)
      const copyData = JSON.parse(JSON.stringify(_this.fromDate));
      copyData.list = JSON.stringify(copyData.list);
      copyData.lotMaintain = JSON.stringify(copyData.lotMaintain);
      copyData.copyTableData = JSON.stringify(this.fromDateList);
      this.addDialog = false;
      this.$router.push({ name: 'ShareMaintenance', query: { ...copyData, type: 1, id: this.keyId } });
    },
    /*份额审批记录*/
    changitem(item, index) {
      this.activeDialog = index;
      this.low = item;
      if (index == "LotAllots") {
        getLotAllots({ id: item.id }).then((res) => {
          this.tableDialog = res.data;
        });
      } else {
        this.DialogParam.id = item.id;
        this.gettableDialog();
      }
    },
    gettableDialog() {
      getauditLot(this.DialogParam).then((res) => {
        this.tableDialog = res.data.data;
        this.Dialogtotal = res.data.totalRows;
      });
    },
    resetDialog() {
      this.activeDialog = "";
    },
    sizeChange(value) {
      this.tableParam.pageSize = value;
      this.gettableData();
    },
  },
};
</script>

<style lang="scss" scoped>
.dialoginfo-title {
  display: flex;
  justify-content: space-between;
  padding: 10px 0 20px 0;
}
.el-input,
.el-select {
  width: 240px;
}
.table_link {
  margin-left: 10px;
  color: $bg_color;
}

.table_link:hover {
  opacity: 0.8;
}
</style>
